package com.ruoyi.project.system.nhmtcnn.test;

/**
 * @author chen0
 * @version 1.0
 * @description: TODO
 * @date 2024/1/20 11:48
 */
import com.ruoyi.project.system.nhmtcnn.domain.FaceDetectionInfo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class ExecuteCMDAndGetOutput {
    public static void main(String[] args) {
        FaceDetectionInfo f = detectImgByFaceNet("D:\\NH\\Img_face\\3.jpg");
        System.out.println(f.getName());
        System.out.println(f.getExitCode());
    }

    public static FaceDetectionInfo detectImgByFaceNet(String img_path) {
        StringBuilder output = new StringBuilder();
        FaceDetectionInfo faceDetectionInfo = new FaceDetectionInfo();
        try {
            // 要执行的 CMD 命令
            String command = "cmd";
            String arg = "/c";
            String cmdCommand = "cd detect_face && conda activate Yolo_face && python detect_img_by_mtcnn.py --img_path " + img_path;
            // python detect_img_by_mtcnn.py --img_path D:\\NH\\Img_face\\4.jpg
            // 使用 ProcessBuilder 构建命令
            ProcessBuilder processBuilder = new ProcessBuilder(command, arg, cmdCommand);

            // 启动进程
            Process process = processBuilder.start();

            // 获取命令的输出流
            InputStream inputStream = process.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            // 读取输出结果
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                output.append(line).append("\n");
            }

            // 等待命令执行完成
            int exitCode = process.waitFor();

            faceDetectionInfo.setName(output.toString());
            faceDetectionInfo.setExitCode(exitCode);

            // 关闭资源
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        return faceDetectionInfo;
    }
}
